//
//  PBPayNowController.m
//  PBHomeDemo
//
//  Created by Playboy on 2018/3/16.
//  Copyright © 2018年 tmkj. All rights reserved.
//

#import "PBPayNowController.h"
#import "PBPaySuccessViewController.h"
#import "WXApi.h"

@interface PBPayNowController ()
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;
@property (strong, nonatomic) IBOutlet UILabel *priceLabel;
@property (strong, nonatomic) IBOutlet UIView *weiChatView;
@property (strong, nonatomic) IBOutlet UIView *alipayView;
@property (strong, nonatomic) IBOutlet UIButton *weiCahtButton;
@property (strong, nonatomic) IBOutlet UIButton *alipayButton;
@property (nonatomic, assign) NSInteger payType;
@end

@implementation PBPayNowController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
}
- (void)configure {
    self.priceLabel.text = [NSString stringWithFormat:@"¥%@",self.payModel.price];
    UITapGestureRecognizer *alipayTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alipayMethod)];
    [self.alipayView addGestureRecognizer:alipayTap];
    UITapGestureRecognizer *weichatTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(weichatMethod)];
    [self.weiChatView addGestureRecognizer:weichatTap];
    [self secondsCountDown:self.timeLabel];
}

- (void)secondsCountDown:(UILabel *)label {
    __block int timeout;
    if (self.creatTime.length > 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"YYYY年MM月dd日 HH:mm:ss";
        // 数字时间戳转化为日期，如果为13位，则需要除以1000，或者去掉后3位
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[[self.creatTime substringWithRange:NSMakeRange(0, 10)] doubleValue]];
        NSString *startTime = [formatter stringFromDate:startDate];
        NSLog(@"%@",startTime);
        NSCalendar *cal = [NSCalendar currentCalendar];
        unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *d = [cal components:unitFlags fromDate:startDate toDate:[NSDate date] options:0];
        int sec = [d hour]*3600+[d minute]*60+[d second];
        timeout = 5400-sec;
        
    }else {
       timeout = 5400;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);//每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout<=0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"计时结束");
            });
        }else {
            int minutes = timeout/60;
            int seconds = timeout%60;
            NSString *strTime = [NSString stringWithFormat:@"%d 分钟 %d 秒", minutes, seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                label.text = [NSString stringWithFormat:@"支付剩余时间  %@",strTime];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)alipayMethod {
    self.payType = 2;
    self.alipayButton.selected = YES;
    self.weiCahtButton.selected = NO;
}
- (void)weichatMethod {
    self.payType = 1;
    self.weiCahtButton.selected = YES;
    self.alipayButton.selected = NO;
}

- (IBAction)surePayButtonClick:(id)sender {
    if (self.payType == 1 || self.payType == 2) {
        [self showAliPayWithCode:self.code];
    }else {
        [self showHint:@"请先选择支付方式"];
    }
}

- (void)showAliPayWithCode:(NSString *)code {
    NSDictionary *param = @{@"code":code,@"payType":[NSString stringWithFormat:@"%zd",self.payType]};
    [TMNetwork requestPostWithParam:param url:@"/order/sign" callback:^(TMBaseReqModel *model) {
        if (model.code == 200) {
            if (self.payType == 1) {
                // 微信支付
                NSDictionary *dic = model.data[@"data"];
                PayReq *request = [[PayReq alloc] init];
                request.partnerId = dic[@"partnerid"];
                request.prepayId= dic[@"prepayid"];
                request.package = dic[@"package"];
                request.nonceStr= dic[@"noncestr"];
                request.timeStamp= [dic[@"timestamp"] intValue];
                request.sign= dic[@"sign"];
                [WXApi sendReq:request];
            }else if (self.payType == 2){
                [TMNetwork alipayWithParam:model.data[@"data"]];
            }
        }else {
            [self showHint:model.message];
        }
    }];
}

#pragma mark - super
- (void)resetNavigationBarItems {
    [super resetNavigationBarItems];
    self.title = @"选择支付方式";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
